/*
 * These files are distributed under the terms of the GNU GPLv2, the GNU General
 * Public version 2. See LICENSE.txt
 */
package fileCommodore.view;

import javax.swing.*;


import org.jdesktop.swingx.*;
import org.jdesktop.swingx.renderer.*;

import fileCommodore.*;
import fileCommodore.model.*;

/**
 * @author nado18@gmail.com, on Jul 15, 2007
 */
public abstract class MyLabelProvider<I extends Comparable<I>>
	extends
		LabelProvider
{
	private MyTableModel<I> model;
	
	public MyLabelProvider(MyTableModel<I> model)
	{
		this.model = model;
	}
	
	public MyTableModel<I> getModel()
	{
		return model;
	}
	
	public void setModel( MyTableModel<I> model )
	{
		this.model = model;
	}
	
	/**
	 * Gets a user-friendly representation of a file size.
	 * 
	 * @param size
	 *            The file size to convert to a friendly string.
	 * @return The friendly representation of the given size, for example 48K
	 *         for 48*1024.
	 */
	public static String friendlySize( long size )
	{
		if (!Config.isFileSizeFriendly())
		{
			return Long.toString( size );
		}
		else
		{
			double d;
			String units;
			if (size >= 1024 * 1024 * 1024)
			{
				d = ( (double) size ) / ( 1024 * 1024 * 1024 );
				units = " G";
			}
			else if (size >= 1024 * 1024)
			{
				d = ( (double) size ) / ( 1024 * 1024 );
				units = " M";
			}
			else if (size >= 1024)
			{
				d = ( (double) size ) / ( 1024 );
				units = " K";
			}
			else
			{
				units = "  ";
				d = size;
			}
			
			d = Math.round( 100 * d ) / 100.0;
			if ((int) d == d)
			{
				return String.format( "%.0f%s", d, units );
			}
			else
			{
				return String.format( "%.2f%s", d, units );
			}
		}
	}
	
	@Override
	protected void format( CellContext context )
	{
		super.format( context );
		
		JXTable table = (JXTable) context.getComponent();
		int row = table.convertRowIndexToModel( context.getRow() );
		JLabel label = rendererComponent;
		I item = getModel().getItemAt( row );
		format( label, item );
	}
	
	public abstract void format( JLabel label, I item );
}
